import global from './global'

import wepy from 'wepy'

export default {
  phone: '15106084131',
  requestUrl: 'https://goktech.s1.natapp.cc/fqnp',
  sessionId: '',
  getUserInfo() {
    return new Promise((resolve, reject) => {
      let cache = global.getUserInfo()
      if (cache) {
        console.log('form cache!')
        resolve(cache)
      } else {
        wepy.login().then((res) => {
          wepy.getUserInfo().then((res) => {
            console.log('getuserinfo success')
            console.log(res)
            global.setUserInfo(res.userInfo)
            resolve(res.userInfo)
          }).catch(reject)
        }).catch(reject)
      }
    })
  },
  getAuther() {
    wepy.getSetting({
      success(res) {
        console.log('auth' + res)
        if (!res.authSetting['scope.record']) {
          wepy.authorize({
            scope: 'scope.record',
            success() {
              wepy.startRecord()
            }
          })
        }
      },
      complete(info) {
        console.log('auth' + info)
      }
    })
  },
  async isWork() {
    let result
    let that = this
    await wepy
      .request({
        url: that.requestUrl + '/fqnp/mini/order/is_work',
        method: 'GET',
        data: {},
        header: {
          openKey: await that.wxGetStorage('sessionId')
        }
      })
      .then(res => {
        if (res && res.data.code === 0) {
          console.log('是值班人员')
          result = 1
        } else if (res && res.data.code !== 0) {
          console.log('不是值班人员')
          result = 2
        } else {
          result = 0
        }
      })
    return result
  },
  async getIsOrder() {
    let result
    let that = this
    await wepy
      .request({
        url: that.requestUrl + '/fqnp/mini/order/order',
        method: 'GET',
        data: {},
        header: {
          openKey: await that.wxGetStorage('sessionId')
        }
      })
      .then(res => {
        console.log(res)
        if (res && res.data.data) {
          result = true
        } else {
          result = false
        }
      })
    return result
  },
  async wxGetStorage(key) {
    try {
      let value = await wepy.getStorageSync(key)
      if (value) {
        // console.log(value)
        return value
      } else {
        return 0
      }
    } catch (e) {
      console.log(e)
    }
  },
  async wxSetStorage(key, value) {
    try {
      await wepy.setStorageSync(key, value)
    } catch (e) {
      console.log(e)
    }
  }
}
